package com.example.myfirstapplication.service

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Binder
import android.os.Build
import android.os.IBinder
import com.example.myfirstapplication.R
import com.example.myfirstapplication.utils.LOG
import kotlinx.android.synthetic.main.activity_thread.view.*
import kotlin.concurrent.thread

class MyService : Service() {

    private val mBinder = DownloadBinder()

    class DownloadBinder : Binder() {
        fun start() {
            LOG.i("DownloadBinder: start download")
        }

        fun getProgress(): Int {
            LOG.i("DownloadBinder: start getProgress")
            return 0
        }

        fun stop() {
            LOG.i("DownloadBinder: stop download")
        }
    }

    override fun onCreate() {
        super.onCreate()
        LOG.i("MyService: onCreate")
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "myServiceChannel",
                "前台服务通知",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            val intent = Intent(this, Thread::class.java)
            val pi = PendingIntent.getActivity(this, 0, intent, 0)
            val notify = Notification.Builder(this, "myServiceChannel")
                .setContentTitle("后台服务通知")
                .setContentText("当前正在执行后台服务")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round))
                .setContentIntent(pi)
                .build()
            startForeground(1, notify)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        LOG.i("MyService: onStartCommand")
        var index = 0
        thread {
            while (index < 10) {
                Thread.sleep(1000)
                LOG.i(index.toString())
                index++
            }
            stopSelf()
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent): IBinder {
        LOG.i("MyService: onBind")
        return mBinder
    }

    override fun onDestroy() {
        super.onDestroy()
        LOG.i("MyService: onDestroy")
    }
}
